#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实时监控上报时间间隔分析脚本
"""

import re
import time
from datetime import datetime

def parse_timestamp_from_log(log_line):
    """从日志中提取时间戳和监控项信息"""
    # 匹配 timestamp 和 itemId 的模式
    timestamp_match = re.search(r'"timestamp":(\d+)', log_line)
    itemid_match = re.search(r'"itemId":(\d+)', log_line)
    
    if timestamp_match and itemid_match:
        timestamp = int(timestamp_match.group(1))
        item_id = int(itemid_match.group(1))
        return timestamp, item_id
    return None, None

def analyze_intervals():
    """分析时间间隔"""
    print("=== 实时上报时间间隔分析 ===")
    print("基于日志提取的实际时间戳")
    print()
    
    # 从之前的日志中提取的已知数据
    known_reports = [
        # 从日志中提取的时间戳
        (1757399011054, 1430255329320961, "system.cpu.util", "14:23:31"),      # CPU使用率
        (1757399011718, 1430255329320962, "system.cpu.num", "14:23:31"),       # CPU核心数
        (1757399013026, 1430255329320963, "vm.memory.size[total]", "14:23:33"), # 内存总量
    ]
    
    print("已知上报记录:")
    for i, (timestamp, item_id, item_key, log_time) in enumerate(known_reports):
        dt = datetime.fromtimestamp(timestamp/1000)
        print(f"{i+1}. {item_key} (ID:{item_id})")
        print(f"   时间戳: {timestamp}")
        print(f"   时间: {dt.strftime('%H:%M:%S.%f')[:-3]} (日志时间: {log_time})")
        
        if i > 0 and known_reports[i-1][1] == item_id:
            # 同一个监控项的前次上报
            interval = timestamp - known_reports[i-1][0]
            print(f"   间隔: {interval}ms ({interval/1000:.1f}s)")
        print()
    
    # 分析vm.memory.size[total]的预期下次上报时间
    memory_total_timestamp = 1757399013026
    memory_total_time = datetime.fromtimestamp(memory_total_timestamp/1000)
    
    print("=== vm.memory.size[total] 间隔分析 ===")
    print(f"最后上报时间戳: {memory_total_timestamp}")
    print(f"最后上报时间: {memory_total_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}")
    print()
    
    # 如果按30秒间隔（备用机制）
    next_30s = memory_total_timestamp + 30000
    next_30s_time = datetime.fromtimestamp(next_30s/1000)
    print(f"如果30秒间隔，下次上报时间戳: {next_30s}")
    print(f"如果30秒间隔，下次上报时间: {next_30s_time.strftime('%H:%M:%S.%f')[:-3]}")
    
    # 如果按60秒间隔（正确配置）
    next_60s = memory_total_timestamp + 60000
    next_60s_time = datetime.fromtimestamp(next_60s/1000)
    print(f"如果60秒间隔，下次上报时间戳: {next_60s}")
    print(f"如果60秒间隔，下次上报时间: {next_60s_time.strftime('%H:%M:%S.%f')[:-3]}")
    print()
    
    print("=== 监控建议 ===")
    print("请观察下一次 vm.memory.size[total] 的上报时间戳:")
    print(f"- 如果接近 {next_30s}，说明仍在使用30秒备用机制（问题未解决）")
    print(f"- 如果接近 {next_60s}，说明已按60秒正确配置上报（问题已解决）")
    
    return next_30s, next_60s

if __name__ == "__main__":
    analyze_intervals()